const express = require("express");
const router = express.Router();
const { Chapter, Course } = require("../../models");
const { Op } = require("sequelize");
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

// 查询章节列表（支持全量/课程筛选）
router.get("/", async (req, res) => {
  try {
    const { currentPage = 1, pageSize = 10, courseId, title } = req.query;

    // 分页参数处理
    const pagination = {
      current: Math.max(parseInt(currentPage), 1),
      size: Math.min(Math.max(parseInt(pageSize), 1), 100), // 限制最大100条/页
    };

    // 构建查询条件
    const where = {};
    if (courseId) where.courseId = { [Op.eq]: courseId };
    if (title) where.title = { [Op.like]: `%${title}%` };

    const { count, rows } = await Chapter.findAndCountAll({
      ...getQueryConfig(),
      where,
      limit: pagination.size,
      offset: (pagination.current - 1) * pagination.size
    });

    success(res, "查询成功", {
      data: rows,
      pagination: {
        ...pagination,
        total: count,
        pages: Math.ceil(count / pagination.size)
      }
    });
  } catch (error) {
    failure(res, error);
  }
});

// 获取章节详情
router.get("/:id", async (req, res) => {
  try {
    const chapter = await getChapterById(req.params.id);
    success(res, "查询成功", { chapter });
  } catch (error) {
    failure(res, error);
  }
});

// 创建章节
router.post("/", async (req, res) => {
  try {
    const chapter = await Chapter.create(filterBody(req.body));
    success(res, "创建成功", { chapter }, 201);
  } catch (error) {
    failure(res, error);
  }
});

// 更新章节
router.put("/:id", async (req, res) => {
  try {
    const chapter = await getChapterById(req.params.id);
    await chapter.update(filterBody(req.body));
    success(res, "更新成功", { chapter });
  } catch (error) {
    failure(res, error);
  }
});

// 删除章节
router.delete("/:id", async (req, res) => {
  try {
    const chapter = await getChapterById(req.params.id);
    await chapter.destroy();
    success(res, "删除成功");
  } catch (error) {
    failure(res, error);
  }
});

// 公共查询配置
function getQueryConfig() {
  return {
    attributes: { exclude: ['courseId'] },
    include: [{
      model: Course,
      as: 'course',
      attributes: ['id', 'name'],
      required: false // 改为非必需关联
    }],
    order: [['rank', 'ASC'], ['id', 'ASC']]
  };
}

// 获取章节详情（带课程信息）
async function getChapterById(id) {
  const chapter = await Chapter.findByPk(id, getQueryConfig());
  if (!chapter) throw new NotFoundError(`章节[${id}]不存在`);
  return chapter;
}

// 请求体过滤
function filterBody(body) {
  return {
    courseId: body.courseId,
    title: body.title,
    content: body.content,
    video: body.video,
    rank: body.rank
  };
}

module.exports = router;